<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    @close="handleClose"
  >
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色标识" prop="code">
            <el-input v-model="form.code" placeholder="请输入角色标识" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="form.sort" :min="0" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 菜单权限 -->
      <el-tab-pane label="菜单权限" name="menus">
        <div class="menu-permission-header">
          <el-button size="small" type="primary" link @click.stop="expandAll">全部展开</el-button>
          <el-button size="small" type="primary" link @click.stop="collapseAll">全部收起</el-button>
          <el-button size="small" type="primary" link @click.stop="checkAll">全选</el-button>
          <el-button size="small" type="primary" link @click.stop="uncheckAll">取消全选</el-button>
        </div>
        <el-scrollbar height="400px">
          <el-tree
            ref="menuTreeRef"
            :data="menuTree"
            :props="{ label: 'title', children: 'children' }"
            show-checkbox
            node-key="id"
            :expanded-keys="expandedKeys"
            @update:expanded-keys="expandedKeys = $event"
            :default-expand-all="false"
            @check="handleMenuCheck"
            class="menu-permission-tree"
          >
            <template #default="{ node, data }">
              <span class="tree-node-label">
                <span class="tree-node-title">{{ data.title }}</span>
                <el-tag v-if="data.type === 1" type="info" size="small" style="margin-left: 8px;">目录</el-tag>
                <el-tag v-else-if="data.type === 2" type="success" size="small" style="margin-left: 8px;">菜单</el-tag>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </el-tab-pane>

      <!-- 权限分配 -->
      <el-tab-pane label="权限分配" name="permissions">
        <el-checkbox-group v-model="form.permission_ids">
          <el-row :gutter="20">
            <el-col :span="8" v-for="permission in permissionList" :key="permission.id">
              <el-checkbox :label="permission.id">
                {{ permission.name }} ({{ permission.code }})
              </el-checkbox>
            </el-col>
          </el-row>
        </el-checkbox-group>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  roleId: {
    type: Number,
    default: null,
  },
})

const emit = defineEmits(['update:modelValue', 'success'])

const dialogVisible = ref(false)
const dialogTitle = ref('新增角色')
const activeTab = ref('basic')
const loading = ref(false)
const formRef = ref(null)
const menuTreeRef = ref(null)

const form = reactive({
  name: '',
  code: '',
  sort: 0,
  status: 1,
  remark: '',
  menu_ids: [],
  permission_ids: [],
})

const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' },
  ],
}

const menuTree = ref([])
const permissionList = ref([])
const expandedKeys = ref([])

// 监听对话框显示
watch(() => props.modelValue, async (val) => {
  dialogVisible.value = val
  if (val) {
    // 先加载菜单树和权限列表
    await Promise.all([loadMenuTree(), loadPermissionList()])
    
    // 等待下一个tick，确保树组件已渲染
    await nextTick()
    
    if (props.roleId) {
      dialogTitle.value = '编辑角色'
      await loadRoleData()
      // 加载角色数据后，设置菜单树选中状态
      await nextTick()
      setTimeout(() => {
        if (menuTreeRef.value && form.menu_ids.length > 0) {
          menuTreeRef.value.setCheckedKeys(form.menu_ids, false)
        }
      }, 150)
    } else {
      dialogTitle.value = '新增角色'
      resetForm()
    }
  }
})

// 监听对话框关闭
watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 处理标签页切换
const handleTabChange = (tabName) => {
  console.log('标签页切换到:', tabName)
  if (tabName === 'menus') {
    // 切换到菜单权限标签页时，确保 Tree 组件已渲染
    nextTick(() => {
      console.log('菜单权限标签页已激活，Tree 组件状态:', {
        hasRef: !!menuTreeRef.value,
        hasData: menuTree.value.length > 0,
        expandedKeys: expandedKeys.value
      })
    })
  }
}

// 加载角色数据
const loadRoleData = async () => {
  try {
    const res = await request.get(`/roles/${props.roleId}`)
    if (res.code === 200) {
      // 处理菜单和权限ID
      const menuIds = res.data.menus || []
      const permissionIds = res.data.permissions || []
      
      Object.assign(form, {
        name: res.data.name,
        code: res.data.code,
        sort: res.data.sort,
        status: res.data.status,
        remark: res.data.remark || '',
        menu_ids: Array.isArray(menuIds) ? menuIds.map(m => typeof m === 'object' ? m.id : m) : [],
        permission_ids: Array.isArray(permissionIds) ? permissionIds.map(p => typeof p === 'object' ? p.id : p) : [],
      })
    }
  } catch (error) {
    ElMessage.error('加载角色数据失败')
  }
}

// 加载菜单树（排除按钮类型，只显示目录和菜单）
const loadMenuTree = async () => {
  try {
    const res = await request.get('/menus', { 
      params: { 
        tree: true, 
        status: 1,
        exclude_buttons: true  // 排除按钮类型的菜单
      } 
    })
    if (res.code === 200) {
      menuTree.value = res.data || []
      // 临时调试：检查数据结构
      if (menuTree.value.length > 0) {
        console.log('菜单树根节点:', menuTree.value[0])
        console.log('第一个菜单的children:', menuTree.value[0]?.children)
        console.log('children数量:', menuTree.value[0]?.children?.length)
      }
    }
  } catch (error) {
    console.error('加载菜单树失败:', error)
    ElMessage.error('加载菜单树失败')
  }
}

// 加载权限列表
const loadPermissionList = async () => {
  try {
    const res = await request.get('/permissions/all/list')
    if (res.code === 200) {
      permissionList.value = res.data
    }
  } catch (error) {
    console.error('加载权限列表失败:', error)
  }
}

// 菜单选择变化
const handleMenuCheck = (data, checked) => {
  if (!menuTreeRef.value) return
  // 只获取完全选中的节点（不包括半选中的父节点）
  // 当所有子节点被选中时，父节点会自动变为完全选中状态
  const checkedKeys = menuTreeRef.value.getCheckedKeys()
  form.menu_ids = checkedKeys
}

// 获取所有节点的keys（递归）
const getAllNodeKeys = (nodes) => {
  let keys = []
  if (!Array.isArray(nodes)) return keys
  
  nodes.forEach(node => {
    keys.push(node.id)
    if (node.children && node.children.length > 0) {
      keys = keys.concat(getAllNodeKeys(node.children))
    }
  })
  return keys
}

// 全部展开
const expandAll = () => {
  if (!menuTreeRef.value) {
    console.warn('Tree 组件未初始化')
    return
  }
  
  const tree = menuTreeRef.value
  
  // 方法1: 通过 store 直接操作节点
  try {
    if (tree.store && tree.store.root) {
      const expandNode = (node) => {
        if (node.childNodes && node.childNodes.length > 0) {
          // 设置节点展开状态
          node.expanded = true
          // 递归展开子节点
          node.childNodes.forEach(child => expandNode(child))
        }
      }
      
      // 展开所有根节点的子节点
      if (tree.store.root.childNodes) {
        tree.store.root.childNodes.forEach(rootNode => expandNode(rootNode))
      }
    }
  } catch (error) {
    console.error('通过 store 展开节点失败:', error)
  }
  
  // 方法2: 使用 expandedKeys（备用方案）
  nextTick(() => {
    const allKeys = getAllExpandableKeys(menuTree.value)
    if (allKeys.length > 0) {
      expandedKeys.value = allKeys
    }
  })
}

// 全部收起
const collapseAll = () => {
  if (!menuTreeRef.value) {
    console.warn('Tree 组件未初始化')
    return
  }
  
  const tree = menuTreeRef.value
  
  // 方法1: 通过 store 直接操作节点
  try {
    if (tree.store && tree.store.root) {
      const collapseNode = (node) => {
        // 设置节点收起状态
        node.expanded = false
        // 递归收起子节点
        if (node.childNodes && node.childNodes.length > 0) {
          node.childNodes.forEach(child => collapseNode(child))
        }
      }
      
      // 收起所有根节点的子节点
      if (tree.store.root.childNodes) {
        tree.store.root.childNodes.forEach(rootNode => collapseNode(rootNode))
      }
    }
  } catch (error) {
    console.error('通过 store 收起节点失败:', error)
  }
  
  // 方法2: 使用 expandedKeys（备用方案）
  nextTick(() => {
    expandedKeys.value = []
  })
}

// 获取所有可展开节点的keys（只包括有子节点的节点）
const getAllExpandableKeys = (nodes) => {
  let keys = []
  if (!Array.isArray(nodes)) return keys
  
  nodes.forEach(node => {
    // 如果节点有子节点，添加到keys中
    if (node.children && Array.isArray(node.children) && node.children.length > 0) {
      keys.push(node.id)
      // 递归获取子节点的keys
      keys = keys.concat(getAllExpandableKeys(node.children))
    }
  })
  return keys
}

// 全选
const checkAll = () => {
  if (!menuTreeRef.value) return
  const allKeys = getAllNodeKeys(menuTree.value)
  menuTreeRef.value.setCheckedKeys(allKeys, false)
  form.menu_ids = allKeys
}

// 取消全选
const uncheckAll = () => {
  if (!menuTreeRef.value) return
  menuTreeRef.value.setCheckedKeys([], false)
  form.menu_ids = []
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    name: '',
    code: '',
    sort: 0,
    status: 1,
    remark: '',
    menu_ids: [],
    permission_ids: [],
  })
  activeTab.value = 'basic'
  expandedKeys.value = []
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  resetForm()
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const url = props.roleId ? `/roles/${props.roleId}` : '/roles'
        const method = props.roleId ? 'put' : 'post'
        const response = await request[method](url, form)
        if (response.code === 200) {
          ElMessage.success(props.roleId ? '更新成功' : '创建成功')
          dialogVisible.value = false
          emit('success')
        }
      } catch (error) {
        if (error.errors) {
          ElMessage.error('验证失败，请检查输入')
        } else {
          ElMessage.error(error.message || '操作失败')
        }
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped lang="scss">
.menu-permission-header {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.menu-permission-tree {
  :deep(.el-tree-node) {
    .el-tree-node__content {
      height: 36px;
      line-height: 36px;
      padding: 0 8px;
      margin: 2px 0;
      border-radius: 4px;
      
      &:hover {
        background-color: var(--el-color-primary-light-9);
      }
    }
    
    .el-tree-node__label {
      font-size: 14px;
      flex: 1;
    }
  }
  
  .tree-node-label {
    display: flex;
    align-items: center;
    flex: 1;
    
    .tree-node-title {
      flex: 1;
    }
  }
  
  :deep(.el-checkbox) {
    margin-right: 8px;
  }
  
  // 缩进调整，使层级更清晰
  :deep(.el-tree-node__children) {
    padding-left: 0;
  }
}

.el-checkbox-group {
  max-height: 400px;
  overflow-y: auto;
}
</style>

